import base64
import hashlib
import json
from datetime import datetime

from getmac import get_mac_address as gma
key = "tianxinyanfa"
def base64_encode(text:str):
    # 将文本编码为字节串
    text_bytes = text.encode('utf-8')

    # 使用 base64 模块进行编码
    base64_bytes = base64.b64encode(text_bytes)

    # 将编码后的字节串转换回文本
    return base64_bytes.decode('utf-8')


def base64_decode(encoded_text:str):
    # 将编码后的文本转换为字节串
    base64_bytes = encoded_text.encode('utf-8')

    # 使用 base64 模块进行解码
    text_bytes = base64.b64decode(base64_bytes)

    # 将解码后的字节串转换回文本
    return text_bytes.decode('utf-8')


def jiaMi(text):
    cipher_text = ""
    key_length = len(key)
    key_as_int = [ord(i.lower()) - ord('a') for i in key]

    for i, char in enumerate(base64_encode(text)):
        if char.isalpha():
            shift = key_as_int[i % key_length]

            shifted_char = chr(((ord(char.lower()) - ord('a') + shift) % 26) + ord('a'))
            if char.isupper():
                shifted_char = shifted_char.upper()
        else:
            shifted_char = char

        cipher_text += shifted_char

    return cipher_text

def machineCode():
    BOARD = gma()
    return hashlib.md5(BOARD.encode(encoding='UTF-8')).hexdigest()
def jieMi(cipher_text):
    decrypted_text = ""
    key_length = len(key)
    key_as_int = [ord(i.lower()) - ord('a') for i in key]

    try:
        for i, char in enumerate(cipher_text):
            if char.isalpha():
                shift = -key_as_int[i % key_length]

                shifted_char = chr(((ord(char.lower()) - ord('a') + shift) % 26) + ord('a'))
                if char.isupper():
                    shifted_char = shifted_char.upper()
            else:
                shifted_char = char

            decrypted_text += shifted_char
    except:
        return None,"秘钥解析失败"
    try:
        data = json.loads(base64_decode(decrypted_text))
    except:
        return None, "秘钥解析失败base64_decode"
    if data["key"] !=machineCode():
        return None, "非绑定注册设备秘钥" + machineCode()
    current_date = datetime.now()
    formatted_date = current_date.strftime('%Y-%m-%d')
    if formatted_date > data["validity"]:
        return None,"注册到期请重新注册" + machineCode()
    return data,None

if __name__ == '__main__':
    # 示例
    serveKey = machineCode()
    print(serveKey)
    text = {
        "validity":"2026-12-20",
        "key":serveKey
    }
    encrypted_text = jiaMi(json.dumps(text))
    print("Encrypted Text:", encrypted_text)

    # decrypted_text,err = jieMi(encrypted_text)
    # print("Decrypted Text:", decrypted_text,err)